//菜单新增/编辑
var id,pid,level,menuCode;
$(function(){
	pid = ly.getUrlParam("pid")||'0';
	id = ly.getUrlParam("id")||'';
	var t = 1;
	iconSelector();
	if(id){
		$(".title span,title").html("编辑");
		$(".form").getForm({
		 	'id':id,
		 	ajaxform:true,
		},function(d){
			level= d.level;
			menuCode = d.menuCode;
			$("#isUsing").getSelect({
				type:"radio",
				asName:"isUsing",
				list:[
					{value:"0",display:"禁用"},
					{value:"1",display:"启用"}
				],
				default:d.isUsing	
			});	
		});	
	}else{
		$("#save-next-btn").removeClass('hide');
		request({
	        url: site.apiUrl + '/menu/selectMenuAllById?id='+pid,
	        type: 'POST',
	        callback: function(r) {
				if(r.code=="rest.success"){
					// debugger;
					var code = r.result[0]&&r.result[0].code||'';
					console.log(code)
					if(code){
						level = parseInt(code.length/3+1);			
					}else{
						level=1
					}
					$("#level").html(level);
					request({
				        url: site.apiUrl + '/menu/selectMenuCreatCodeById',
				        data:{
				        	'id':r.result[0]&&r.result[0].id||'',
				        	'level':level
				    	},
		        		ajaxform:false,
				        type: 'POST',
				         ajaxform:true,
				        callback: function(r) {
							if(r.code=="rest.success"){
								menuCode = r.result;
								$("#menuCode").html(menuCode);
				        	}else{
				        		ly.toast(r.msg);
				        	}
				        }
					});
	        	}else{
	        		ly.toast(r.msg);
	        	}
	        }
		});
		$("#isUsing").getSelect({
			type:"radio",
			asName:"isUsing",
			list:[
				{value:"0",display:"禁用"},
				{value:"1",display:"启用"}
			],
			default:1	
		});	
	}
	//提交回到列表页
	$("body").on("click",".save-btn",function(){
		event.preventDefault();
		var success =  $('#form').validate('submitValidate');
		if(success){
			if(id){
				var opts = 'menu-list.html';
				if(type==1){
					opts = "refresh";
				}
				$(".form").submitForm({
					id:id,
					isUsing:$("#isUsing input:checked").val(),
					parentId:pid,
					level:level,
					menuCode:menuCode,
					url:site.apiUrl+"/menu/updateMenuThis"
				},"menu-list.html"); //成功后跳转的页面,可为空	

			}else{
				var type = $(this).data("type");
				var opts = '';
				if(type==1){
					opts = "refresh";
				}
				$(".form").submitForm({
					parentId:pid,
					level:level,
					isUsing:$("#isUsing input:checked").val(),
					menuCode:menuCode,
					url:site.apiUrl+"/menu/insertMenu",
					ajaxform:false,
				},'menu-list.html',opts); //成功后跳转的页面,可为空	

			}
		}
	})
});
